import axios from 'axios'
export default {
    namespaced: true,
    state: () => ({
        cart: []
    }),
    mutations: {
        updateCart(state, cart) {
            state.cart = cart
        },
        updateState(state, payload) {
            let index = state.cart.findIndex(itme => itme.id == payload.id)
            state.cart[index].goods_state = payload.value
        },
        updataCount(state, payload) {
            let index = state.cart.findIndex(itme => itme.id == payload.id)
            state.cart[index].goods_count = payload.value
        },
        updataisAll(state, val) {
            state.cart.forEach(item => item.goods_state = val)
        }
    },
    actions: {
        //发送ajax  因为是异步函数  要放在action 里面
        async getCartList(context) {
            // 3.2 发送请求
            const res = await axios.get('https://www.escook.cn/api/cart')
            // console.log(res);
            context.commit('updateCart', res.data.list)
        }
    },
    getters: {
        allPrice(state) {
            return state.cart
                .filter((item) => item.goods_state)
                .reduce((sum, item) => (sum += item.goods_count * item.goods_price), 0);
        },
        allCount(state) {
            return state.cart
                .filter((item) => item.goods_state)
                .reduce((sum, item) => (sum += item.goods_count), 0);
        },

    }
} 